package com.demo.autotest.service;

import com.demo.autotest.common.exception.DuplicateException;
import com.demo.autotest.database.domain.Function;
import com.demo.autotest.database.mapper.FunctionMapper;
import com.demo.autotest.dto.FunctionDTO;
import com.demo.autotest.request.QueryRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.UUID;

@Service    // 定义service层
@Transactional(rollbackFor = Exception.class)
public class FunctionService {

    @Resource
    private FunctionMapper functionMapper;

    public void saveFunction(Function function){
        Function old = functionMapper.getFunctionByName(function.getProjectId(), function.getName());
        if(old != null && !old.getId().equals(function.getId())){
            throw new DuplicateException("本项目已有该函数名称");
        }
        if(function.getId() != null && !function.getId().equals("")){
            function.setUpdateTime(System.currentTimeMillis());
        }else{
            function.setId(UUID.randomUUID().toString());
            function.setCreateUser(function.getUpdateUser());
            function.setCreateTime(System.currentTimeMillis());
            function.setUpdateTime(System.currentTimeMillis());
        }
        functionMapper.saveFunction(function);
    }

    public void delete(String id){
        functionMapper.delete(id);
    }

    public Function getFunctionDetail(String id){
        return functionMapper.getFunctionDetail(id);
    }

    public List<FunctionDTO> getFunctionList(QueryRequest request){
        if(request.getCondition() != null && !request.getCondition().equals("")){
            request.setCondition("%" + request.getCondition() + "%");
        }
        return functionMapper.getFunctionList(request);
    }

}
